package es.masterd.lector_rss.db;

import es.masterd.lector_rss.db.FeedsDB.Posts;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class FeedsProvider extends ContentProvider {
	
	/** 
	 * Definición de constantes necesarias para el Provider
	 */
	public static final String PROVIDER_NAME = "es.masterd.blog";
	public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME);
	
	public static final int POST = 1;
	public static final int POST_ID = 2;
	
	private static final UriMatcher uriMatcher;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(PROVIDER_NAME, "post", POST);
		uriMatcher.addURI(PROVIDER_NAME, "post/#", POST_ID);
	}
	
	/**
	 * Atributos de la clase
	 */
	private SQLiteDatabase feedsDB;

	@Override
	public boolean onCreate() {
		FeedsSQLHelper dbHelper = new FeedsSQLHelper(getContext());
		feedsDB = dbHelper.getWritableDatabase();
		return (feedsDB == null) ? false : true;
	}
	
	@Override
	public String getType(Uri uri) {
		switch(uriMatcher.match(uri)) {
			case POST: // Para un conjunto de posts
				return("vnd.android.cursor.dir/vnd.masterd.post");
			case POST_ID:
				return("vnd.android.cursor.item/vnd.masterd.post");
			default:
				throw new IllegalArgumentException ("Unsupported URI:" + uri);
		}
	}

	@Override
	public int delete(Uri uri, String where, String[] whereargs) {
		int count = 0;
		
		switch(uriMatcher.match(uri)) {
			case POST:
				count = feedsDB.delete(Posts.NOMBRE_TABLA, where, whereargs);
				break;
			case POST_ID:
				String id = uri.getPathSegments().get(1);
				String whereId = Posts._ID + " = " + id + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : "");
				count = feedsDB.delete(Posts.NOMBRE_TABLA, whereId, whereargs);
				break;
			default:
				throw new IllegalArgumentException("Unknown URI" + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return(count);
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long rowID = feedsDB.insert(Posts.NOMBRE_TABLA, "", values);

		// Si todo ha ido OK devolveremos su URI
		if (rowID > 0) {
			Uri baseUri = Uri.parse("content://" + PROVIDER_NAME + "/post");
			Uri _uri = ContentUris.withAppendedId(baseUri, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			getContext().getContentResolver().notifyChange(baseUri, null);
			return(_uri);
		}
		throw new SQLException("Failed to insert row into" + uri);
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		builder.setTables(Posts.NOMBRE_TABLA);
		
		if(uriMatcher.match(uri) == POST_ID) {
			String id = uri.getPathSegments().get(1);
			builder.appendWhere(Posts._ID + " = " + id);
		}
		if(sortOrder == null || sortOrder == "") {
			sortOrder = Posts.DEFAULT_SORT_ORDER;
		}
		
		Cursor c = builder.query(feedsDB, projection, selection, selectionArgs, null, null, sortOrder);
		// Registramos los cambios para que se enteren nuestros observadores
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return(c);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		int count = 0;
		
		switch(uriMatcher.match(uri)) {
			case POST:
				count = feedsDB.update(Posts.NOMBRE_TABLA, values, selection, selectionArgs);
				break;
			case POST_ID:
				String id = uri.getPathSegments().get(1);
				String selectionId = Posts._ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
				count = feedsDB.update(Posts.NOMBRE_TABLA, values, selectionId, selectionArgs);
				break;
			default:
				throw new IllegalArgumentException("Unknown URI:" + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return(count);
	}
}